<template>
  <!-- 试题信息 -->
  <el-row class="user-info-form" type="flex" justify="center">
    <el-col>
      <el-form label-width="150px" :model="questionInfoForm" :rules="questionInfoFormRules" ref="questionInfoForm" @submit.native.prevent>
        <el-form-item label="题型：" prop='questionType'>
          <el-radio-group v-model="questionInfoForm.questionType" :disabled="oldInfo.id ? true : false" @change="changeQuestionType">
            <el-radio-button label=1>判断题</el-radio-button>
            <el-radio-button label=2>单选题</el-radio-button>
            <el-radio-button label=3>多选题</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <p class="model-split-text">设置题干</p>
        <el-form-item label="题干：" prop='content'>
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入题干文字内容" v-model="questionInfoForm.content">
          </el-input>
        </el-form-item>
        <el-form-item label="图片：" prop='pictures'>
          <el-upload :action="QINIUUPLOADURL" :multiple="false" ref="upload" list-type="picture-card" :data="dryPicQiniuData" :on-success="function(res, file, fileList) {return handleAvatarSuccess(res, file, fileList, 'dryPicQiniuData')}" :on-remove="function(file, fileList) {return handleRemovePic(file, fileList, 'dryPicQiniuData')}" :on-error="function(res) {return handleError(res, 'dryPicQiniuData')}" :before-upload="function(file){return beforeAvatarUpload(file, 'dryPicQiniuData')}" :on-preview="$imgPreview" :file-list="dryPicQiniuData.fileList" :limit="9" :on-exceed="function(files, fileList) {return handleExceed(files, fileList, 'dryPicQiniuData')}" accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="短视频：" prop='video'>
          <el-upload class="upload-demo" drag :action="QINIUUPLOADURL" :multiple="false" ref="videoUpload" :data="dryVideoQiniuData" :on-success="function(res, file, fileList) {return handleAvatarSuccess(res, file, fileList, 'dryVideoQiniuData')}" :on-remove="function(file, fileList) {return handleRemovePic(file, fileList, 'dryVideoQiniuData')}" :on-error="function(res) {return handleError(res, 'dryVideoQiniuData')}" :before-upload="function(file){return beforeAvatarUpload(file, 'dryVideoQiniuData')}" :file-list="dryVideoQiniuData.fileList" :limit="1" :on-exceed="function(files, fileList) {return handleExceed(files, fileList, 'dryVideoQiniuData')}" accept=".avi,.rmvb,.wmv,.mp4">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__text">支持扩展名：.avi、.rmvb、.wmv、.mp4</div>
          </el-upload>
          <video style="display: none;" controls="controls" id="uploadVideo" width="200" height="100"></video>
        </el-form-item>
        <p class="model-split-line"></p>

        <p class="model-split-text">设置答题选项</p>
        <!-- 判断题 -->
        <template v-if="questionInfoForm.questionType == 1">
          <el-form-item label="答案：" prop='answer'>
            <el-radio-group v-model="questionInfoForm.answer">
              <el-radio v-for="(item, index) in optionList" :key="index" :label="index">{{ item.optionContent }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="" label-width="0" prop='answer'>
            <el-row class="question-option-list">
              <el-col :span="1">
                <p>&nbsp;</p>
              </el-col>
              <el-col :span="3">
                <p class="text-center">选项</p>
              </el-col>
              <el-col :span="16">
                <p class="text-center">选项文字</p>
              </el-col>
              <el-col :span="4">
                <p class="text-center">答案</p>
              </el-col>
            </el-row>
            <el-row class="question-option-list" v-for="(item, index) in optionList" :key="index">
              <el-col :span="1">
                <i class="el-icon-error color-1" @click="deleteOption(index)"></i>
              </el-col>
              <el-col :span="3">
                <div class="text-center">{{ mapOption(index) }}</div>
              </el-col>
              <el-col :span="16">
                <el-input v-model="item.optionContent"></el-input>
              </el-col>
              <el-col :span="4" class="text-center">
                <el-radio v-if="questionInfoForm.questionType==2" v-model="questionInfoForm.answer" :label="index">{{''}}</el-radio>
                <el-checkbox v-else v-model="item.isAnswer" :label="1" :true-label="1" :false-label="0" @change="checkboxChange">{{''}}</el-checkbox>
              </el-col>
            </el-row>
            <el-row>
              <el-button type="primary" icon="el-icon-plus" circle @click="addOption"></el-button>
            </el-row>
          </el-form-item>
        </template>
        <p class="model-split-line"></p>

        <p class="model-split-text">设置答案解析</p>
        <el-form-item label="解析文字：" prop='pictures'>
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入解析文字内容" v-model="questionInfoForm.analysisContent">
          </el-input>
        </el-form-item>
        <el-form-item label="解析图片：" prop='pictures'>
          <el-upload :action="QINIUUPLOADURL" :multiple="false" ref="upload" list-type="picture-card" :data="parsePicQiniuData" :on-success="function(res, file, fileList) {return handleAvatarSuccess(res, file, fileList, 'parsePicQiniuData')}" :on-remove="function(file, fileList) {return handleRemovePic(file, fileList, 'parsePicQiniuData')}" :on-error="function(res) {return handleError(res, 'parsePicQiniuData')}" :before-upload="function(file){return beforeAvatarUpload(file, 'parsePicQiniuData')}" :on-preview="$imgPreview" :file-list="parsePicQiniuData.fileList" :limit="9" :on-exceed="function(files, fileList) {return handleExceed(files, fileList, 'parsePicQiniuData')}" accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <p class="model-split-line"></p>

        <p class="model-split-text">添加标签</p>
        <!-- 添加标签组件 -->
        <select-label :selectVal="questionInfoForm.labelContent" ref="selectLabel"></select-label>
        <p class="model-split-line"></p>
        <el-form-item label-width="0" class="verifyidentity-button">
          <el-button @click.stop="closeFun" round>取消</el-button>
          <el-button type="primary" @click="saveQuestion('questionInfoForm')" round>保存</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>
<script>
import util from '@/utils/util'
import { qnToken } from '@/api/api'
import SelectLabel from '../../Common/SelectLabel'
import { saveOrUpdateQuestion } from '@/api/exam'

let TYPEMAP = {
  dryPicQiniuData: '题干图片',
  dryVideoQiniuData: '题干短视频',
  parsePicQiniuData: '解析图片',
}

export default {
  name: 'QuestionInfo',
  props: {
    closeFun: {
      type: Function,
      required: true,
    },
    oldInfo: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  components: {
    SelectLabel,
  },
  data() {
    return {
      // 上传图片携带的默认参数
      qiniuDefaultData: {
        token: '',
      },
      questionInfoForm: {
        id: 0,
        questionType: 1, // 题目类型（1判断题 2单选题 3多选题）
        content: '', // 题干
        contentPics: '', // 题干图片
        video: '', // 题干小视频
        optionsStr: '', // 选项
        answer: '', // 正确答案
        analysisContent: '', // 解析文字
        analysisPics: '', // 解析图片
        labelContent: '', // 标签
        updateAccount: this.$store.state.userinfo.accountName || '', // 更新人账号（新建与创建账号一致）
        createAccount: this.$store.state.userinfo.accountName || '', // 创建人账号
      },
      questionInfoFormRules: {
        questionType: [{ required: true, message: '请选择题型', trigger: 'change' }],
        content: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请选择正确答案', trigger: 'change' }],
      },
      // 题干图片
      dryPicQiniuData: {
        key: '',
        fileList: [],
      },
      // 题干短视频
      dryVideoQiniuData: {
        key: '',
        fileList: [],
      },
      // 答题选项
      optionList: [],
      // 解析图片
      parsePicQiniuData: {
        key: '',
        fileList: [],
      },
    }
  },
  created() {
    let that = this
    this.questionInfoForm.questionType = this.oldInfo.questionType
    // 新增时初始默认判断题
    if (Object.keys(that.oldInfo).length < 1) {
      this.changeQuestionType(1)
    } else {
      // 设置选项回显
      this.changeQuestionType(that.oldInfo.questionType, JSON.parse(that.oldInfo.optionsStr))
      this.checkboxChange()
    }
    // 获取token
    qnToken({}).then((result) => {
      this.qiniuDefaultData.token = result.data
      $.extend(this.dryPicQiniuData, this.qiniuDefaultData)
      $.extend(this.dryVideoQiniuData, this.qiniuDefaultData)
      $.extend(this.parsePicQiniuData, this.qiniuDefaultData)

      that.$nextTick(() => {
        // 如果有历史数据
        if (Object.keys(that.oldInfo).length > 0) {
          for (var key in that.questionInfoForm) {
            // 答案、更新人不需要赋值； 另外，如果是复制过来的试题不需要把创建人赋值
            if (
              (key != 'answer' && key != 'updateAccount' && key != 'createAccount') ||
              (key == 'createAccount' && that.oldInfo.id)
            ) {
              that.questionInfoForm[key] = that.oldInfo[key]
            }
          }
          // 设置题干图片回显
          that.oldInfo.contentPics
            ? $.each(that.oldInfo.contentPics.split(','), (index, url) => {
                let arr = url.split('/')
                that.dryPicQiniuData.fileList.push({
                  name: arr[arr.length - 1],
                  url: url,
                })
              })
            : ''
          // 设置题干短视频
          that.oldInfo.video
            ? $.each(that.oldInfo.video.split(','), (index, url) => {
                let arr = url.split('/')
                that.dryVideoQiniuData.fileList.push({
                  name: arr[arr.length - 1],
                  url: url,
                })
              })
            : ''
          // 设置解析图片回显
          that.oldInfo.analysisPics
            ? $.each(that.oldInfo.analysisPics.split(','), (index, url) => {
                let arr = url.split('/')
                that.parsePicQiniuData.fileList.push({
                  name: arr[arr.length - 1],
                  url: url,
                })
              })
            : ''

          // 如果是非多选题型,设置this.questionInfoForm.answer值
          if (that.oldInfo.questionType != 3) {
            for (let i = 0, len = that.optionList.length; i < len; i++) {
              if (that.optionList[i].isAnswer == 1) {
                that.questionInfoForm.answer = i
              }
            }
          }
          // 标签的回显
        }
      })
    })
  },
  methods: {
    // 切换题型
    changeQuestionType(key, oldList) {
      // 清空答案
      this.questionInfoForm.answer = ''
      if (oldList) {
        // 选项有历史记录
        this.optionList = oldList
      } else {
        if (key == 1) {
          // 判断题
          this.optionList = [
            {
              optionMark: 'A',
              optionContent: '正确',
              isAnswer: 0,
            },
            {
              optionMark: 'B',
              optionContent: '错误',
              isAnswer: 0,
            },
          ]
        } else {
          // 单选题 或 多选题
          this.optionList = [
            {
              optionMark: 'A',
              optionContent: '',
              isAnswer: 0,
            },
            {
              optionMark: 'B',
              optionContent: '',
              isAnswer: 0,
            },
            {
              optionMark: 'C',
              optionContent: '',
              isAnswer: 0,
            },
            {
              optionMark: 'D',
              optionContent: '',
              isAnswer: 0,
            },
          ]
        }
      }

      // 清空校验提示
      this.$nextTick(() => {
        this.$refs['questionInfoForm'].clearValidate()
      })
    },
    // 映射选项
    mapOption(index) {
      let MAPLIST = {
        0: 'A',
        1: 'B',
        2: 'C',
        3: 'D',
        4: 'E',
        5: 'F',
        6: 'G',
        7: 'H',
        8: 'I',
        9: 'J',
        10: 'K',
      }

      return MAPLIST[index] || ''
    },
    // 增加选项
    addOption() {
      if (this.optionList.length < 8) {
        this.optionList.push({
          optionMark: 'B',
          optionContent: '',
          isAnswer: 0,
        })
        this.optionList.forEach((n, i) => {
          n.optionMark = this.mapOption(i)
        })
      } else {
        this.$message.warning('答题选项不能超过9个')
        return false
      }
    },
    // 删除选项
    deleteOption(index) {
      // 至少保留两个选项
      if (this.optionList.length > 2) {
        this.optionList.splice(index, 1)
        this.optionList.forEach((n, i) => {
          n.optionMark = this.mapOption(i)
        })
      } else {
        this.$message.warning('答题选项不能少于2个')
        return false
      }
    },
    // 多选的checkbox值变化
    checkboxChange(val) {
      let hasAnswer = false
      for (let i = 0, len = this.optionList.length; i < len; i++) {
        if (this.optionList[i].isAnswer == 1) {
          hasAnswer = true
          break
        }
      }
      if (hasAnswer) {
        this.questionInfoForm.answer = '1'
      } else {
        this.questionInfoForm.answer = ''
      }
    },
    // 重命名和校验
    beforeAvatarUpload(file, type, obj) {
      var fielLocal = file.name.split('.')
      var fielType = '.' + fielLocal[fielLocal.length - 1]
      var fielLocalName = fielLocal[0]
      if (obj) {
        obj[type].key = fielLocalName + '_' + new Date().getTime() + fielType
      } else {
        this[type].key = fielLocalName + '_' + new Date().getTime() + fielType
      }
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt20M = file.size / 1024 / 1024 < 20
      if (type === 'dryVideoQiniuData') {
        let video = file
        let url = URL.createObjectURL(video)
        let dom = document.getElementById('uploadVideo')
        dom.src = url
        return this.judgeVideoDuration()
      } else {
        if (!isJPG && !isPNG) {
          this.$message.error('图片只能是 JPG/PNG 格式!')
          return false
        }
        if (!isLt20M) {
          this.$message.error('图片大小不能超过 20MB!')
          return false
        }
      }
    },
    // 上传成功
    handleAvatarSuccess(res, file, fileList, type, obj) {
      if (obj) {
        obj[type].fileList = fileList
      } else {
        this[type].fileList = fileList
      }
      // if(type === 'dryPicQiniuData') {
      //     this.questionInfoForm.contentPics = util.ilinkArrHandle.getqiniuPicUrlArr(this.dryPicQiniuData.fileList).toString() // 题干图片
      // } else if(type === 'dryVideoQiniuData') {
      //     this.questionInfoForm.video = util.ilinkArrHandle.getqiniuPicUrlArr(this.dryVideoQiniuData.fileList).toString() // 题干短视频
      // } else if(type === 'parsePicQiniuData') {
      //     this.questionInfoForm.analysisPics = util.ilinkArrHandle.getqiniuPicUrlArr(this.parsePicQiniuData.fileList).toString() // 解析图片
      // }
    },
    // 删除成功
    handleRemovePic(file, fileList, type, obj) {
      if (obj) {
        obj[type].fileList = fileList
      } else {
        this[type].fileList = fileList
      }
    },
    handleError(res, type) {
      this.$message({
        message: `${TYPEMAP[type]}上传失败`,
        duration: 2000,
        type: 'warning',
      })
    },
    handleExceed(files, fileList, type) {
      if (type === 'dryVideoQiniuData') {
        this.$message.warning(`${TYPEMAP[type]}最多只能上传1个，如需重新上传请先删除原先视频`)
      } else {
        this.$message.warning(`${TYPEMAP[type]}最多只能上传9张，如需重新上传请先删除原先图片`)
      }
    },
    // 判断短视频时长
    judgeVideoDuration() {
      let that = this
      return new Promise(function (resolve, reject) {
        let dom = document.getElementById('uploadVideo')
        dom.oncanplaythrough = (e) => {
          if (e.target.duration > 60) {
            that.$message.error('视频长度最多60秒')
            reject()
          } else {
            // 上传视频
            resolve()
          }
        }
      })
    },
    // 保存
    saveQuestion(formName) {
      // 阻止事件冒泡
      event.stopPropagation()
      let that = this
      // 校验表单
      that.$refs[formName].validate((valid) => {
        if (valid) {
          let parames = that.questionInfoForm
          // 题干图片
          parames.contentPics = util.ilinkArrHandle
            .getqiniuPicUrlArr(that.dryPicQiniuData.fileList)
            .toString()
          // 题干视频
          parames.video = util.ilinkArrHandle
            .getqiniuPicUrlArr(that.dryVideoQiniuData.fileList)
            .toString()
          // 选项值
          parames.optionsStr = JSON.stringify(this.optionList)
          // 解析图片
          parames.analysisPics = util.ilinkArrHandle
            .getqiniuPicUrlArr(that.parsePicQiniuData.fileList)
            .toString()
          // 添加的标签
          parames.labelContent = that.$refs['selectLabel'].getSelectLabel().join(',')
          // 移除正确答案
          delete parames.answer
          saveOrUpdateQuestion(parames).then((res) => {
            if (res.status === 200) {
              // 提交成功
              that.$message.success('保存成功！')
              setTimeout(function () {
                that.closeFun(true)
              }, 1000)
            }
          })
        } else {
          return false
        }
      })
    },
  },
  computed: {
    answer() {
      return this.questionInfoForm.answer
    },
  },
  watch: {
    answer(val, oldVal) {
      if (val !== '' && this.questionInfoForm.questionType != '3') {
        for (let i = 0, len = this.optionList.length; i < len; i++) {
          if (i == val) {
            this.optionList[i].isAnswer = 1
          } else {
            this.optionList[i].isAnswer = 0
          }
        }
        this.$refs['questionInfoForm'].clearValidate()
      }
    },
  },
}
</script>
<style lang="scss">
.question-option-list {
  margin: 5px 0;
  line-height: 40px;
  .el-radio__label,
  .el-checkbox__label {
    padding-left: 0;
  }
}
</style>
<style lang="scss" scoped>
.model-split-text {
  margin: 10px 0;
  color: #409eff;
  font-size: 16px;
  font-weight: bold;
}
.model-split-line {
  margin-top: 10px;
  border-bottom: 1px solid #DCDFE6;
}
.el-icon-upload {
  margin-top: 20px;
}
.el-icon-error {
  cursor: pointer;
}
</style>
